﻿using System.Data;

namespace Singer.Core.DataExtensions;

public static class DataTableExtensions
{
    public static List<T> ToList<T>(this DataTable dt) where T : class
    {
        var list = new List<T>();
        if (dt == null || dt.Rows.Count == 0)
            return list;
        Type type = typeof(T);
        foreach (DataRow dr in dt.Rows)
        {
            T? t = Activator.CreateInstance(type, true) as T;
            if (t != null)
            {
                foreach (var propertie in type.GetProperties())
                {
                    if (dt.Columns.Contains(propertie.Name))
                        propertie.SetValue(t, dr[propertie.Name]);
                }
                list.Add(t);
            }
        }
        return list;
    }

    public static T? ToModel<T>(this DataRow dr) where T : class
    {
        Type type = typeof(T);
        T? t = Activator.CreateInstance(type, true) as T;
        if (t == null)
            return null;
        foreach (var propertie in type.GetProperties())
        {
            if (dr.Table.Columns.Contains(propertie.Name))
                propertie.SetValue(t, dr[propertie.Name]);
        }
        return t;
    }
}
